import { getScreenSize, loadImage } from ".";
import { Season } from "@/type/game";
import { shadowMatrix } from "@/config/shadow";
import { addCollisionArea } from "./collision";
import type { CollisionArea } from "./collision";
import type { TreeSpriteConfig } from "@/config/treeConfig";
import { TreeConfigs, TreeType, TreeGrowthStage } from "@/config/treeConfig";

// 树木实例
export interface Tree {
  id: string;
  type: TreeType;
  stage: TreeGrowthStage;
  x: number; // 树的x坐标
  y: number; // 树的y坐标
  season: Season;
  shakeAmount?: number; // 摇晃的幅度
  shakeDirection?: number; // 摇晃的方向
  isShaking?: boolean; // 是否正在摇晃
  visible: boolean; // 是否可见
  alpha?: number; // 透明度
}

// 树木资源管理器
class TreeManager {
  private treeSprites: HTMLImageElement | null = null;
  private treeSpriteConfigs = TreeConfigs as Record<
    TreeType,
    Record<Season, Record<TreeGrowthStage, TreeSpriteConfig>>
  >;

  private trees: Tree[] = [];
  private treeCollisionIndices: Map<string, number> = new Map(); // 用于存储树木碰撞区域的索引
  private treesNeedSorting: boolean = true; // 是否需要重新排序
  public savedCollisionAreas: Map<string, CollisionArea> = new Map(); // 保存树木碰撞区域

  private shadowCanvas: HTMLCanvasElement | null = null;
  private shadowCtx: CanvasRenderingContext2D | null = null;
  private shadowNeedsUpdate: boolean = false;

  /**
   * 创建树木碰撞区域
   * @param tree 树木实例
   * @returns 碰撞区域对象
   */
  private createTreeCollisionArea(tree: Tree): CollisionArea | null {
    const config = this.getTreeConfig(tree);
    if (!config) return null;

    if (tree.stage === TreeGrowthStage.MATURE) {
      return {
        type: "rectangle",
        x: tree.x - (config.parts?.crown?.width || 0) / 2,
        y: tree.y - (config.parts?.crown?.height || 0),
        width: config.parts?.crown?.width,
        height: config.parts?.crown?.height,
      };
    }
    if (
      tree.stage === TreeGrowthStage.STUMP ||
      tree.stage === TreeGrowthStage.STAGE_1 ||
      tree.stage === TreeGrowthStage.STAGE_2 ||
      tree.stage === TreeGrowthStage.STAGE_3
    ) {
      return {
        type: "rectangle",
        x: tree.x,
        y: tree.y,
        width: config.width,
        height: config.height,
      };
    }

    return null;
  }

  /**
   * 重置树木碰撞区域
   */
  restoreTreeCollisions(): void {
    import("./collision").then(({ enableCollisionAreas }) => {
      this.trees.forEach((tree) => {
        const collisionIndex = this.treeCollisionIndices.get(tree.id);
        if (collisionIndex !== undefined) {
          enableCollisionAreas(collisionIndex);
        } else {
          // 如果碰撞索引不存在，重新创建碰撞区域
          const collisionArea = this.createTreeCollisionArea(tree);
          if (collisionArea) {
            const index = addCollisionArea(collisionArea);
            this.treeCollisionIndices.set(tree.id, index);
          }
        }
      });
    });
  }

  /**
   * 禁用树木碰撞区域
   */
  disableTreeCollisions(): void {
    import("./collision").then(({ disableCollisionAreas }) => {
      this.trees.forEach((tree) => {
        const collisionIndex = this.treeCollisionIndices.get(tree.id);
        if (collisionIndex !== undefined) {
          disableCollisionAreas(collisionIndex);
        }
      });
    });
  }

  /**
   * 加载树木精灵图
   * @param spritePath 树木精灵图的路径
   */
  async loadTreeSprites(spritePath: string): Promise<void> {
    try {
      this.treeSprites = await loadImage(spritePath);
      console.log("树木精灵图加载成功");
    } catch (error) {
      console.error("加载树木精灵图失败：", error);
    }
  }

  /**
   * 添加树木
   * @param tree 树木实例
   * @returns 添加的树木实例
   */
  // addTree(tree: Omit<Tree, "id">): Tree {
  addTree(tree: Omit<Tree, "id">) {
    const gridSize = 16;

    // 计算网格对齐后的X和Y坐标
    const gridX = Math.floor(tree.x / gridSize) * gridSize + gridSize / 2;
    const gridY = Math.floor(tree.y / gridSize) * gridSize;

    const newTree = {
      ...tree,
      id: `tree_${Date.now()}_${Math.random().toString(36).slice(2, 9)}`,
      isShaking: false,
      shakeAmount: 0,
      shakeDirection: 1,
      x: gridX, // 使用网格对齐后的X坐标
      y: gridY, // 使用网格对齐后的Y坐标
    };
    this.trees.push(newTree);

    // 创建并添加碰撞区域
    const collisionArea = this.createTreeCollisionArea(newTree);

    if (collisionArea) {
      const index = addCollisionArea(collisionArea);
      this.treeCollisionIndices.set(newTree.id, index);
      this.savedCollisionAreas.set(newTree.id, collisionArea);
    }
    this.sortTrees();
    this.shadowNeedsUpdate = true;
    // return newTree;
  }

  /**
   * 按照树木底部的Y坐标排序
   */
  private sortTrees(): void {
    this.trees.sort((a, b) => {
      const configA = this.getTreeConfig(a);
      const configB = this.getTreeConfig(b);

      let bottomA = a.y;
      let bottomB = b.y;

      // 计算树木A的底部位置
      if (a.stage === TreeGrowthStage.MATURE && configA?.parts?.trunk) {
        bottomA = a.y + (configA.parts.trunk.height || 0);
      } else if (configA?.height) {
        bottomA = a.y + configA.height;
      }

      // 计算树木B的底部位置
      if (b.stage === TreeGrowthStage.MATURE && configB?.parts?.trunk) {
        bottomB = b.y + (configB.parts.trunk.height || 0);
      } else if (configB?.height) {
        bottomB = b.y + configB.height;
      }

      return bottomA - bottomB;
    });

    // 排序完成后，更新标记
    this.treesNeedSorting = false;
  }

  /**
   * 移除树木
   * @param treeId 树木的唯一标识符
   */
  removeTree(treeId: string): void {
    this.trees = this.trees.filter((tree) => tree.id !== treeId);
    this.treesNeedSorting = true;
    this.shadowNeedsUpdate = true;
  }

  /**
   * 获取所有树木
   * @returns 所有树木的数组
   */
  getAllTrees(): Tree[] {
    return this.trees;
  }

  /**
   * 清除所有树木
   */
  clearAllTrees(): void {
    this.trees = [];
    this.shadowNeedsUpdate = true;
  }

  /**
   * 设置树木的可见性
   * @param visible 可见性
   */
  setTreeVisibility(visible: boolean) {
    this.trees.forEach((tree) => {
      tree.visible = visible;
    });

    // 如果是进入房屋，禁用所有树木碰撞区域
    if (!visible) {
      this.treeCollisionIndices.forEach((index) => {
        import("./collision").then(({ disableCollisionAreas }) => {
          disableCollisionAreas(index);
        });
      });
    } else {
      // 如果是返回农场，恢复树木碰撞区域
      this.treeCollisionIndices.forEach((index) => {
        import("./collision").then(({ enableCollisionAreas }) => {
          enableCollisionAreas(index);
        });
      });
    }
    this.shadowNeedsUpdate = true;
  }

  /**
   * 更新树木透明度基于玩家位置
   * @param playerX 玩家的x坐标
   * @param playerY 玩家的y坐标
   */
  updateTreeTransparency(
    playerX: number,
    playerY: number,
    playerWidth: number,
    playerHeight: number
  ): void {
    const minAlpha = 0.2; // 最小透明度
    const transitionSpeed = 0.1; // 透明度过渡速度

    this.trees.forEach((tree) => {
      const config = this.getTreeConfig(tree);
      if (!config) return;

      // 计算树木的矩形区域
      let treeLeft, treeRight, treeTop, treeBottom;

      if (
        tree.stage === TreeGrowthStage.MATURE &&
        config.parts?.crown &&
        config.parts?.trunk
      ) {
        // 计算树冠和树干的组合区域
        const crownWidth = config.parts.crown.width || 0;
        const crownHeight = config.parts.crown.height || 0;
        const trunkHeight = config.parts.trunk.height || 0;

        // 水平方向
        treeLeft = tree.x - crownWidth * 2;
        treeRight = treeLeft + crownWidth * 3;

        // 垂直方向
        treeTop = tree.y - crownHeight - trunkHeight - trunkHeight / 4;
        treeBottom = tree.y - trunkHeight + trunkHeight / 8;
      } else {
        // 其他阶段 - 使用配置的宽高
        treeLeft = tree.x - config.width / 2;
        treeRight = treeLeft + config.width;
        treeTop = tree.y - config.height;
        treeBottom = tree.y;
      }

      // 计算玩家的矩形区域
      const playerLeft = playerX - playerWidth / 2;
      const playerRight = playerLeft + playerWidth;
      const playerTop = playerY - playerHeight;
      const playerBottom = playerY;

      // 检测矩形重叠
      const isOverlapping = !(
        playerRight < treeLeft ||
        playerLeft > treeRight ||
        playerBottom < treeTop ||
        playerTop > treeBottom
      );

      // 设置透明度
      const targetAlpha = isOverlapping ? minAlpha : 1;
      // 线性平滑过渡
      tree.alpha =
        tree.alpha !== undefined
          ? tree.alpha + (targetAlpha - tree.alpha) * transitionSpeed
          : targetAlpha;
    });
  }

  // 渲染单个树木
  renderSingleTree(ctx: CanvasRenderingContext2D, tree: Tree): void {
    if (!this.treeSprites) {
      console.error("树木精灵图尚未加载");
      return;
    }

    const config =
      this.treeSpriteConfigs[tree.type]?.[tree.season]?.[tree.stage];

    if (!config) {
      console.warn(
        `未找到树木配置: ${tree.type}, ${tree.season}, ${tree.stage}`
      );
      return;
    }

    ctx.save();

    if (tree.alpha !== undefined) {
      ctx.globalAlpha = tree.alpha;
    }

    if (config.parts) {
      // 计算树木底部的中心位置
      const trunkWidth = config.parts.trunk?.width || 0;
      const trunkHeight = config.parts.trunk?.height || 0;

      const trunkX = tree.x - trunkWidth / 2; // 确保树的底部在X轴上居中
      const trunkY = tree.y - trunkHeight;

      // 渲染树桩
      if (config.parts.crown) {
        const crown = config.parts.crown;
        const crownX =
          trunkX +
          trunkWidth / 2 -
          crown.width -
          crown.width / 2 +
          (crown.offsetX || 0);
        const crownY = trunkY - crown.height + (crown.offsetY || 0);

        ctx.drawImage(
          this.treeSprites,
          crown.x,
          crown.y,
          crown.width,
          crown.height,
          crownX,
          crownY,
          crown.width,
          crown.height
        );
      }

      // 渲染树干
      if (config.parts.trunk) {
        const trunk = config.parts.trunk;
        ctx.drawImage(
          this.treeSprites,
          trunk.x,
          trunk.y,
          trunk.width,
          trunk.height,
          trunkX + (trunk.offsetX || 0),
          trunkY + (trunk.offsetY || 0) - (config.parts.crown?.height || 0),
          trunk.width,
          trunk.height
        );

        // const newTree = {
        //   ...tree,
        //   id: `tree_${Date.now()}_${Math.random().toString(36).slice(2, 9)}`,
        //   isShaking: false,
        //   shakeAmount: 0,
        //   shakeDirection: 1,
        //   x: trunkX + (trunk.offsetX || 0), // 使用网格对齐后的X坐标
        //   y: trunkY + (trunk.offsetY || 0) - (config.parts.crown?.height || 0), // 使用网格对齐后的Y坐标
        // };
        // this.trees.push(newTree);

        // // 创建并添加碰撞区域
        // const collisionArea = this.createTreeCollisionArea(newTree);
      }
    } else {
      // 其他阶段按普通方式渲染
      ctx.drawImage(
        this.treeSprites,
        config.x,
        config.y,
        config.width,
        config.height,
        tree.x,
        tree.y,
        config.width,
        config.height
      );
    }

    // 恢复画布状态
    ctx.restore();
  }

  updateTrees(deltaTime: number): void {}

  /**
   * 获取树木的配置
   * @param tree 树木实例
   * @returns 树木的配置
   */
  getTreeConfig(tree: Tree): TreeSpriteConfig | undefined {
    return this.treeSpriteConfigs[tree.type]?.[tree.season]?.[tree.stage];
  }

  /**
   * 初始化阴影画布
   * @param width 画布宽度
   * @param height 画布高度
   */
  private initShadowCanvas(width: number, height: number): void {
    if (!this.shadowCanvas) {
      this.shadowCanvas = document.createElement("canvas");
      this.shadowCtx = this.shadowCanvas.getContext("2d", { alpha: true });
    }

    if (
      this.shadowCanvas.width !== width ||
      this.shadowCanvas.height !== height
    ) {
      this.shadowCanvas.width = width;
      this.shadowCanvas.height = height;
      this.shadowNeedsUpdate = true;
    }
  }

  /**
   * 渲染树木阴影
   * @param ctx 画布上下文
   * @param tree 树木实例
   * @param config 树木的配置
   */
  public renderAllTreeShadows(ctx: CanvasRenderingContext2D): void {
    const { width, height } = ctx.canvas;

    if (
      !this.shadowCanvas ||
      this.shadowCanvas.width !== width ||
      this.shadowCanvas.height !== height
    ) {
      this.initShadowCanvas(width, height);
    }

    // 只有在需要更新时才重新渲染阴影
    if (this.shadowCtx && this.shadowNeedsUpdate) {
      // 清除阴影画布
      this.shadowCtx.clearRect(0, 0, width, height);

      // 在阴影画布上渲染所有树木的阴影
      this.shadowCtx.fillStyle = "rgb(101, 67, 33)";

      // 遍历所有树木并渲染它们的阴影
      this.trees.forEach((tree) => {
        if (!tree.visible) return;

        let pixelSize = tree.stage === TreeGrowthStage.MATURE ? 2 : 1;
        const config = this.getTreeConfig(tree);
        if (!config) return;

        const shadowX = tree.x - (shadowMatrix[0].length * pixelSize) / 2;
        let shadowY;

        if (tree.stage === TreeGrowthStage.MATURE && config.parts) {
          const crownHeight = config.parts.crown?.height || 0;
          shadowY =
            tree.y - (shadowMatrix.length * pixelSize) / 2 - crownHeight / 2;
        } else if (tree.stage === TreeGrowthStage.STUMP) {
          shadowY =
            tree.y - (shadowMatrix.length * pixelSize) / 2 + config.height / 4;
        } else {
          shadowY = tree.y - (shadowMatrix.length * pixelSize) / 2;
        }

        for (let y = 0; y < shadowMatrix.length; y++) {
          for (let x = 0; x < shadowMatrix[y].length; x++) {
            if (shadowMatrix[y][x] === 1) {
              this.shadowCtx &&
                this.shadowCtx.fillRect(
                  Math.round(shadowX + x * pixelSize),
                  Math.round(shadowY + y * pixelSize),
                  pixelSize,
                  pixelSize
                );
            }
          }
        }
      });

      // 标记阴影已更新
      this.shadowNeedsUpdate = false;
    }

    // 绘制阴影画布到主画布
    if (this.shadowCanvas) {
      ctx.save();
      ctx.globalAlpha = 0.3;
      ctx.drawImage(this.shadowCanvas, 0, 0);
      ctx.restore();
    }
  }
}

export const treeManager = new TreeManager();
